package com.uaijug.dengue.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.uaijug.dengue.core.Foco;
import com.uaijug.dengue.core.Foto;
import com.uaijug.dengue.core.RedeSocial;
import com.uaijug.dengue.core.Usuario;
import com.uaijug.dengue.dao.PMF;
import com.uaijug.dengue.entidade.Constantes;

public class DatastoreUploadServlet extends AbstractUploadServlet {
	private static final long serialVersionUID = -7943725592967493243L;
	private BlobstoreService blobService = BlobstoreServiceFactory.getBlobstoreService();
	PersistenceManager pm = PMF.get().getPersistenceManager();
	@Override
	protected void showForm(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String uploadUrl = blobService.createUploadUrl("/datastore");
        req.setAttribute("uploadUrl", uploadUrl);
		req.getRequestDispatcher("datastore.jsp").forward(req, resp);
	}

	@Override
	protected void handleSubmit(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

		try {
			
			Map<String, BlobKey> blobs = blobService.getUploadedBlobs(req);

			Usuario notificador = new Usuario();
			Usuario resolutor = new Usuario();
			Foco foco = new Foco();
			List<Foto> fotos = new ArrayList<Foto>();
			
	        Set<String> fotosAttr = blobs.keySet();
	        for (String fotoAttr : fotosAttr) {
	        	Foto foto = new Foto();
	        	BlobKey blobKey = blobs.get(fotoAttr);
	        	BlobInfo info = new BlobInfoFactory().loadBlobInfo(blobKey);
	        	foto.setFotoData(blobKey);
	        	foto.setContentType(info.getContentType());
	        	foto.setDataCaptura(info.getCreation());
	        	foto.setFoco(foco);
	        	fotos.add(foto);
			}
			foco.setDetalhe(req.getParameter(Constantes.FOCO_CLASS.DETALHE));
			foco.setLatitude(Long.parseLong(req.getParameter(Constantes.FOCO_CLASS.LATITUDE)));
			foco.setLongitude(Long.parseLong(req.getParameter(Constantes.FOCO_CLASS.LONGITUDE)));
			notificador.setNome(req.getParameter(Constantes.USUARIO_CLASS.NOME));
			notificador.setEmail(req.getParameter(Constantes.USUARIO_CLASS.EMAIL));
			notificador.setSenha("senha");
			resolutor.setNome(req.getParameter(Constantes.USUARIO_CLASS.NOME));
			resolutor.setEmail(req.getParameter(Constantes.USUARIO_CLASS.EMAIL));
			resolutor.setSenha("senha");
			
			RedeSocial redeSocial = new RedeSocial();
			redeSocial.setComunidade(1);
			redeSocial.setMensagem("Notifiquei um foco");
			redeSocial.setLoguinUsuario("admin");
			redeSocial.setSenha("senha");
			List<RedeSocial> redesSociais = new ArrayList<RedeSocial>();
			notificador.setRedesSociais(redesSociais);
			resolutor.setRedesSociais(redesSociais);
			foco.setNotificador(notificador);
			//Resolucao resolucao = new Resolucao();
			//resolucao.setFoto(foto);
			//resolucao.setResolutor(resolutor);
			foco.setFotos(fotos);
			foco.setDataCriacao(new Date());
			
			Transaction tx = pm.currentTransaction();
			try {
		        tx.begin();
		        pm.makePersistent(foco);
		        tx.commit();
		    } finally {
		        if (tx.isActive()) {
		            tx.rollback();
		        }
		    }
			resp.sendRedirect("datastore?action=display&id=" + foco.getKey().getId());
		} catch (IOException e) {
			throw new ServletException(e);
		}
	}

	@Override
	protected void showRecord(Long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		//cria o identificador do objeto a partir do id
		Key keyId = KeyFactory.createKey(Foco.class.getSimpleName(), Long.parseLong(req.getParameter("id")));
	    Foco foco = pm.getObjectById(Foco.class, keyId);
	    
		resp.setContentType(foco.getFotos().get(0).getContentType());
		
		//a partir do blobkey recupera a imagem no datastore
		BlobKey key = foco.getFotos().get(0).getFotoData();
		BlobInfo info = new BlobInfoFactory().loadBlobInfo(key);
		BlobstoreService service = BlobstoreServiceFactory.getBlobstoreService();
		byte[] bytes = service.fetchData(key, 0, info.getSize());
		
//		ImagesService imagesService = ImagesServiceFactory.getImagesService();
//        Image oldImage = ImagesServiceFactory.makeImage(bytes);
//        Transform resize = ImagesServiceFactory.makeResize(Math.round(oldImage.getWidth() * 0.5f), Math.round(oldImage.getHeight() * 0.5f));
//        Image newImage = imagesService.applyTransform(resize, oldImage);
//
//        byte[] newImageData = newImage.getImageData();
		
		resp.getOutputStream().write(bytes);
		resp.flushBuffer();
	}
}
